package com.zl.roomdesignserver.controller;

import com.zl.roomdesignserver.entity.design.MaterialEntity;
import com.zl.roomdesignserver.entity.design.UploadFileEntity;
import com.zl.roomdesignserver.service.DesignService;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangli on 2018/5/6 19:30.<br/>
 */
@RestController
public class DesignController {

    @Autowired
    DesignService designService;

    @PostMapping("/design/material")
    public Object getMaterial() {
        return designService.getAllMaterial();
    }

    @RequestMapping("/upload")
    @ResponseBody
    public Object handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("userName") String name, @RequestParam("phone") Long phone) {
        UploadFileEntity entity = new UploadFileEntity();
        entity.setUserName(name);
        entity.setPhone(phone);
        entity.setUploadTime((int) (System.currentTimeMillis() / 1000));
        if (!file.isEmpty()) {
            try {
                File path = new File(ResourceUtils.getURL("classpath:").getPath());
                if (!path.exists()) path = new File("");
                System.out.println("path:" + path.getAbsolutePath());
                File upload = new File(path.getAbsolutePath(), "static/images/upload/");
                if (!upload.exists()) upload.mkdirs();
                System.out.println("upload url:" + upload.getAbsolutePath());
                String p = upload + "/" + file.getOriginalFilename();
                entity.setFileName("images/upload/" + file.getOriginalFilename());
                File test = new File(p);
                int i = 0;
                while (test.exists()) {
                    p = upload + "/" + i + file.getOriginalFilename();
                    entity.setFileName("images/upload/" + i + file.getOriginalFilename());
                    test = new File(p);
                    i++;
                }
                file.transferTo(new File(p));
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
            return designService.save(entity);
        } else {
            throw new RuntimeException("上传失败，因为文件是空的");
        }
    }

    @RequestMapping("/getAll")
    @ResponseBody
    public Object getAll() {
        return designService.getAll();
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(@RequestParam("id") String id) {
        designService.delete(id);
        return "ok";
    }

    @RequestMapping("/getByUser")
    @ResponseBody
    public Object getByUser(@RequestParam("phone") Long phone) {
        return designService.getByUser(phone);
    }


    @RequestMapping("/design/insertAll")
    @ResponseBody
    public Object insertAll() {
        List<MaterialEntity> list = new ArrayList<>();

        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) path = new File("");
            System.out.println("path:" + path.getAbsolutePath());
            File material = new File(path.getAbsolutePath(), "static/material/");
            if (material.exists() && material.isDirectory()) {
                File[] files = material.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isDirectory()) {
                            File[] imgs = file.listFiles();
                            if (imgs != null) {
                                for (File img : imgs) {
                                    MaterialEntity entity = new MaterialEntity();
                                    entity.setType(file.getName());
                                    entity.setName(img.getName());
                                    entity.setFileName("material/" + file.getName() + "/" + img.getName());
                                    list.add(entity);
                                }
                            }

                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

        designService.insertAll(list);
        return designService.getAllMaterial();
    }

    @RequestMapping("/design/uploadMulti")
    @ResponseBody
    public Object uploadMulti(@RequestParam("file") List<MultipartFile> files, @RequestParam(value = "kind", required = false) String kind) {

        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) path = new File("");
            System.out.println("path:" + path.getAbsolutePath());
            File material = new File(path.getAbsolutePath(), "static/material/");
            if (kind == null || kind.length() == 0) {
                kind = "unknown";
            }
            File fileKind = new File(material.getAbsolutePath(), kind);
            if (!fileKind.exists()) {
                fileKind.mkdirs();
            }
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {

                    MaterialEntity entity = new MaterialEntity();
                    entity.setType(kind);
//                    entity.setName(img.getName());
//                    entity.setFileName("material/"+file.getName()+"/"+img.getName());

                    String p = fileKind.getAbsolutePath() + "/" + file.getOriginalFilename();
                    entity.setFileName("material/" + kind + "/" + file.getOriginalFilename());
                    entity.setName(getFileNameNoEx(file.getOriginalFilename()));
                    File test = new File(p);
                    int i = 0;
                    while (test.exists()) {
                        p = fileKind.getAbsolutePath() + "/" + i + file.getOriginalFilename();
                        entity.setFileName("material/" + kind + "/" + i + file.getOriginalFilename());
                        entity.setName(i + file.getOriginalFilename());
                        test = new File(p);
                        i++;
                    }
                    file.transferTo(new File(p));
                    designService.saveMaterial(entity);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return "ok";
    }

    public String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }






}
